package cn.itsource.hrm.web.controller;

import cn.itsource.hrm.fastdfs.FastDfsApiOpr;
import cn.itsource.util.AjaxResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
@CrossOrigin
public class FastdfsController {
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file){
        //file.getOriginalFilename()获取原生的文件名
        //获取扩展名
        String exName= FilenameUtils.getExtension(file.getOriginalFilename());
        //将文件上传到云服务器
        try {
            String uploadPath = FastDfsApiOpr.upload(file.getBytes(),exName);
            return AjaxResult.me().setResultObj(uploadPath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败");
        }
    }
    //上传文件
    @PostMapping("/uploadfile")
    public AjaxResult uploadFile(@RequestBody byte[] file,@RequestParam("extName") String extName ){
        //将文件上传到云服务器
        try {
            String uploadPath = FastDfsApiOpr.upload(file,extName);
            return AjaxResult.me().setResultObj(uploadPath);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("文件上传失败");
        }
    }
    @PostMapping("/download")
    public byte[] download(@RequestParam("filePath") String filePath){
        //根据下载的路径 将下载路径拆分成需要的格式
        //数据库中文件的下载路径：/group1/M00/00/01/wKgAaF5atm6ABrDeAACBNnMr71A396.zip
        //如果是以/开头name就进行截去
        String path=filePath.startsWith("/")?filePath.substring(1):filePath;
        //然后得到的新的下载路径，确定第一个/所在的位置
        int i = path.indexOf("/");
        //获得groupName
        String groupName=path.substring(0,i);
        //获得fileName
        String fileName=path.substring(i+1);
        // byte[] download(String groupName,String fileName)

        try {
            byte[] bytes = FastDfsApiOpr.download(groupName, fileName);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
